package com.sun.controller;

import com.sun.config.Result;
import com.sun.entity.User;
import com.sun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: 黄日盛
 * @ClassName: WebController
 * @Description: web页面控制
 * @Date: 2025-03-21 10:32
 * @Version: 1.0
 */
@Controller
public class WebController {

    @Autowired
    private UserService userService;
    // 上传文件的地址
    // 修改为系统绝对路径（示例）


    // 登录处理
    @PostMapping("/login")
    public String login(@RequestParam("name") String username,
                        @RequestParam("password") String password,
                        Map<String,Object> maps,
                        HttpSession session, Model model)  {
        User user = userService.login(username, password);

        if (user != null) {
            // 登录成功，将用户信息存储到Session
            session.setAttribute("user", user);
            model.addAttribute("user", user);

            maps.put("msg", "成功登录！");
            return "redirect:/main";
        } else {
           maps.put("msg", "用户名或密码不正确!");
            return "login";
        }
    }

    @GetMapping("/main")
    public String main(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        model.addAttribute("currentUser", user);
        return "main";
    }

    //去登录页面
    @GetMapping("/toLogin")
    public String toLogin(HttpSession session ,Map<String,Object> maps){
        session.removeAttribute("msg");
        maps.put("msg", "");
        return "login";
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 移除Session中的用户信息
        session.removeAttribute("user");
        // 使Session失效
        session.invalidate();

        // 跳转到登录页面
        return "redirect:index";
    }


    /**
     * 去到注册页面
     * @return
     */
    @GetMapping("/toRegister")
    public String toRegister(){
        return "register";
    }

    /**
     * 用户注册
     * @param
     * @param model
     * @return
     */
    private static final String AVATAR_UPLOAD_DIR = System.getProperty("user.dir") + "/uploads/avatars/";
    @PostMapping("/register")
    public String register(
            @RequestParam("name") String name,
            @RequestParam("sex") String sex,
            @RequestParam("age") int age,
            @RequestParam("password") String password,
            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
            Model model,
            HttpSession session) {

        System.out.println("接收到文件：" + (avatar != null ? avatar.getOriginalFilename() : "NULL"));

        // 处理头像上传
        String avatarFileName = null;
        if (avatar != null && !avatar.isEmpty()) {
            // 检查文件类型
            String contentType = avatar.getContentType();
            if (!contentType.startsWith("image/")) {
                model.addAttribute("msg", "只支持图片文件");
                return "register";
            }

            // 创建上传目录（如果不存在）
            File uploadDir = new File(AVATAR_UPLOAD_DIR);
            if (!uploadDir.exists()) {
                boolean dirCreated = uploadDir.mkdirs();
                if (!dirCreated) {
                    System.out.println("目录创建失败，路径：" + AVATAR_UPLOAD_DIR);
                    model.addAttribute("msg", "目录创建失败");
                    return "register";
                }
            }

            // 生成唯一的文件名
            String originalFilename = avatar.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            avatarFileName = UUID.randomUUID().toString().replace("-", "") + fileExtension;

            // 保存文件
            try {
                avatar.transferTo(new File(AVATAR_UPLOAD_DIR + avatarFileName));
                System.out.println("文件保存成功，路径：" + AVATAR_UPLOAD_DIR + avatarFileName);
            } catch (IOException e) {
                System.out.println("文件上传失败：" + e.getMessage());
                model.addAttribute("msg", "文件上传失败: " + e.getMessage());
                return "register";
            }
        }
        avatarFileName = "http://localhost:8080/uploads/avatars/" + avatarFileName;

        // 创建用户对象
        User user = new User();
        user.setName(name);
        user.setSex(sex);
        user.setAge(age);
        user.setPassword(password);
        user.setAvatar(avatarFileName); // 存储头像文件名
        System.out.println("用户头像文件名：" + user.getAvatar());

        // 检查用户名是否存在
        User existingUser = userService.selectUserByname(name);

        if (existingUser == null) { // 如果用户名不存在
            // 转换性别显示为中文
            if ("male".equalsIgnoreCase(sex)) {
                user.setSex("男");
            } else if ("female".equalsIgnoreCase(sex)) {
                user.setSex("女");
            }

            userService.addUser(user);
            session.setAttribute("registerSuccess", true);
            model.addAttribute("msg", "注册成功！");
            return "login"; // 跳转到登录页面
        } else {
            model.addAttribute("msg", "用户名已经存在！");
            return "register"; // 返回注册页面并显示错误信息
        }
    }
}